#include <QApplication>
#include <QtGui>
#include <string>
#include <sstream>
#include <cstdio>

#include "QtApp.h"
#include "Server.h"
#include "../Common/PokerTool.h"

using namespace std;

void QtApp::createPage()
{
	cout << "---------------------------------------------"<< endl;
	cout << "----Création d'un nouvel onglet pour la partie numero (" << Game::getGame()->numeroOfGame << ")" << endl;
	//mdealerise a jour du titre
	string s = "<font color=\"#0000FF\"><h2>En fin de la partie</h2></font>";

	cout << "Game::getGame()->winner : " << Game::getGame()->gameinfo.winner;
	if(Game::getGame()->gameinfo.getwinner( Game::getGame()->gameinfo.getPlayers() ) == 1)
	{
		s += "<font color=\"#FF0000\"><h3>" + Game::getGame()->gameinfo.getPlayer(1).getName().toStdString();
		s += "("+Game::getGame()->gameinfo.getPlayer(1).getBankroll()+") : Gagnant";
		s += "(" +Game::getGame()->gameinfo.getPlayer(1).getCombinationLabel().toStdString()+")";
		s += "</h3></font>";

		s += "<font color=\"#FF0000\"><h3>" + Game::getGame()->gameinfo.getPlayer(2).getName().toStdString();
		s += "("+Game::getGame()->gameinfo.getPlayer(2).getBankroll()+") : Perdant";
		s += "(" +Game::getGame()->gameinfo.getPlayer(2).getCombinationLabel().toStdString()+")";
		s += "</h3></font>";
	}
	else
	{
		s += "<font color=\"#FF0000\"><h3>" + Game::getGame()->gameinfo.getPlayer(1).getName().toStdString();
		s += "("+Game::getGame()->gameinfo.getPlayer(1).getBankroll()+") : Perdant";
		s += "(" +Game::getGame()->gameinfo.getPlayer(1).getCombinationLabel().toStdString()+")";
		s += "</h3></font>";

		s += "<font color=\"#FF0000\"><h3>" + Game::getGame()->gameinfo.getPlayer(2).getName().toStdString();
		s += "("+Game::getGame()->gameinfo.getPlayer(2).getBankroll()+") : Gagnant";
		s += "(" +Game::getGame()->gameinfo.getPlayer(2).getCombinationLabel().toStdString()+")";
		s += "</h3></font>";
	}
	titre->setText(s.c_str() );

	// A la création du nouvel onglet, vérification si pas fin de jeu, et dans ce cas on arrête le Timer
	endGame(Game::getGame()->gameinfo.getPlayers()[1],Game::getGame()->gameinfo.getPlayers()[2]);

	//Incrémantation du nombre de partie joué
	Game::getGame()->numeroOfGame++;

	string num = "Partie " ;

	//Correction du bug d'affichage
	if(Game::getGame()->numeroOfGame > NBGAME)
		num.append(PokerTool::intToString( 1 ) );
	else
		num.append(PokerTool::intToString( Game::getGame()->numeroOfGame) );

	// Création du nouvelle onglet
	QWidget *page = new QWidget;
	tab->addTab(page, num.c_str() );

	// Déplace sur le nouvelle onglet
	//tab->setCurrentIndex(Game::getGame()->numeroOfGame+1);

	//Création d'un nouveau layout
	gridLayout = new QGridLayout();
	gridLayoutCardPlayer[0] = new QGridLayout();
	gridLayoutCardPlayer[1] = new QGridLayout();
	gridLayoutCardFlop = new QGridLayout();

	gridLayout->addLayout(gridLayoutCardPlayer[0],2,0);
	gridLayout->addLayout(gridLayoutCardFlop,2,1);
	gridLayout->addLayout(gridLayoutCardPlayer[1],2,2);

	//Ajout du layout
	page->setLayout(gridLayout);

 	//Create title
	titre = new QLabel("<font color=\"#FF0000\"><h2>Partie</h2></font>");

	//Rattache le titre à la fenêtre courante
	gridLayout->addWidget(titre,0,0);
}
/*
 * Affiche une carte (image) dans l'application, le x et y sont les 2 ponts de position a l'écran
 */
void QtApp::printCard(Card &c,QGridLayout *gridLayout,int x, int y)
{
	QLabel  *label_img2  = new QLabel();
	QPixmap *pixmap_img2 = new QPixmap(c.getImgPath().toStdString().c_str());
	label_img2->setPixmap(*pixmap_img2);

	gridLayout->addWidget(label_img2,x,y);
}
void QtApp::printCard(Card &c,QGridLayout *gridLayout,int x, int y,int row,int colmn,Qt::Alignment ali)
{
	QLabel  *label_img2  = new QLabel();
	QPixmap *pixmap_img2 = new QPixmap(c.getImgPath().toStdString().c_str());
	label_img2->setPixmap(*pixmap_img2);

	gridLayout->addWidget(label_img2,x,y,row,colmn,ali);
}
void QtApp::updateDeliveryRiver()
{
	printCard(Game::getGame()->gameinfo.getBoardCards()[4],gridLayoutCardFlop,0,4);
}
void QtApp::updateDeliveryTurn()
{
	printCard(Game::getGame()->gameinfo.getBoardCards()[3],gridLayoutCardFlop,0,3);
}
void QtApp::updateDeliveryFlop()
{
	printCard(Game::getGame()->gameinfo.getBoardCards()[0],gridLayoutCardFlop,0,0);
	printCard(Game::getGame()->gameinfo.getBoardCards()[1],gridLayoutCardFlop,0,1);
	printCard(Game::getGame()->gameinfo.getBoardCards()[2],gridLayoutCardFlop,0,2);
}
void QtApp::updateDeliveryPreFlop()
{
	//Titre flop
	flo = new QLabel("<font color=\"#FF0000\"><h2>Flop</h2></font>");
	gridLayout->addWidget(flo,1,1);

	// Gestion affiche dans le layout /
	printCard(Game::getGame()->gameinfo.getPlayer(1).hand[0],gridLayoutCardPlayer[0],0,0);
	printCard(Game::getGame()->gameinfo.getPlayer(1).hand[1],gridLayoutCardPlayer[0],0,1,1,4,Qt::AlignLeft);
	printCard(Game::getGame()->gameinfo.getPlayer(2).hand[0],gridLayoutCardPlayer[1],0,2,1,2,Qt::AlignRight);
	printCard(Game::getGame()->gameinfo.getPlayer(2).hand[1],gridLayoutCardPlayer[1],0,3);

	string label1 ="<font color=\"#0000FF\"><h3>"+Game::getGame()->gameinfo.getPlayer(1).getName().toStdString();
	label1.append (" - blind("+Game::getGame()->gameinfo.getPlayer(1).getBlind(Game::getGame()->gameinfo.getBigBlind())+") -argent("+Game::getGame()->gameinfo.getPlayer(1).getBankroll()+")</h3></font>");
	label1.append("<table border=\"1\"><tr><th>No</th><th>Tour</th><th>Somme mise</th><th>Argent</th><th>Action</th><th>Mise en cours</th></tr>");

	libelleInformation[1] = new QLabel();
	libelleInformation[1]->setText( label1.c_str() );
	gridLayout->addWidget(libelleInformation[1],1,0);

	string label2 = "<font color=\"#0000FF\"><h3>"+Game::getGame()->gameinfo.getPlayer(2).getName().toStdString();
	label2.append(" - blind("+Game::getGame()->gameinfo.getPlayer(2).getBlind(Game::getGame()->gameinfo.getBigBlind())+") -argent("+Game::getGame()->gameinfo.getPlayer(2).getBankroll()+")</h3></font>");
	label2.append("<table border=\"1\"><tr><th>No</th><th>Tour</th><th>Somme mise</th><th>Argent</th><th>Action</th><th>Mise en cours</th></tr>");

	libelleInformation[2] = new QLabel();
	libelleInformation[2]->setText( label2.c_str() );
	gridLayout->addWidget(libelleInformation[2],1,2);
}
string QtApp::createTabHTML(string libellePlaying,Player &player)
{
	string ch;

	ch.append(libelleInformation[Game::getGame()->gameinfo.getCurrentPlayer()]->text().toStdString() );

	//ch.append(libelleInformation[player.getPosition()]->text().toStdString() );
	ch.append("<tr><td>");
	if((Game::getGame()->gameinfo.getPlayer(1).getBet()==Game::getGame()->gameinfo.getPlayer(2).getBet())
			&& Game::getGame()->twoPlayerOnPlay >=2 )
	{
		ch.append("<b>");
	}
	//ch.append(player.getName().toStdString()+"_");
	ch.append(Game::getGame()->getCountActiontoString());
	//ch.append("_");
	//ch.append( player.getBlind( Game::getGame()->gameinfo.getBigBlind() ) );

	if( (Game::getGame()->gameinfo.getPlayer(1).getBet()==Game::getGame()->gameinfo.getPlayer(2).getBet() )
			&& Game::getGame()->twoPlayerOnPlay >=2 )
	{
		ch.append("</b>");
	}
	ch.append("</td><td>");
	ch.append(libellePlaying+"</td><td>" + player.getSommeMiseString() +"</td>");
	ch.append("<td>"+player.getBankroll()+"</td><td>"+player.getAction().toStdString()+"</td><td>");
	if((Game::getGame()->gameinfo.getPlayer(1).getBet()==Game::getGame()->gameinfo.getPlayer(2).getBet())
			&& Game::getGame()->twoPlayerOnPlay >=2 )
	{
		ch.append("<b>");
	}
	ch.append(player.getBet());
	if((Game::getGame()->gameinfo.getPlayer(1).getBet()==Game::getGame()->gameinfo.getPlayer(2).getBet())
			&& Game::getGame()->twoPlayerOnPlay >=2 )
	{
		ch.append("</b>");
	}
	ch.append("</td></tr>");

	return ch;
}
/*
 * Met à jour l'interface graphique a chaque action d'un joueur
 */
void QtApp::upadteInterfaceGraphicOnPlayer(Player &player)
{
	//mise a jour du titre
	string s = "<font color=\"#FF0000\"><h2>" + player.getName().toStdString() + "("+player.getAction().toStdString()+")</h2></font>";
	titre->setText(s.c_str() );

	//mise a jour du tableau des actions/choix d'un joueur
	string ch;
	//si les somme sont égaux pour corriger le bueg d'affichage, on affiche l'état précédent
/*
	if(Game::getGame()->gameinfo.getPlayer(1).getBet()==Game::getGame()->gameinfo.getPlayer(2).getBet() && Game::getGame()->twoPlayerOnPlay >= 2)
	{
		//0 pre-lop,1 flop, 2 turn, 3 river
		if(Game::getGame()->gameinfo.getGameState()==0)
		{
			ch.append(createTabHTML(libState[3],player));
		}
		else
		{
			ch.append(createTabHTML(libState[Game::getGame()->gameinfo.getGameState()-1],player));
		}
	}
	else
	{
*/
		ch.append(createTabHTML(libState[Game::getGame()->gameinfo.getGameState()],player));
/*
	}
*/
	libelleInformation[Game::getGame()->gameinfo.getCurrentPlayer()]->setText(ch.c_str() );

	//libelleInformation[player.getPosition()]->setText(ch.c_str() );

	// int to string : pot
	string spot =  PokerTool::intToString( Game::getGame()->gameinfo.getPot() );

	string stex = "<font color=\"#FF0000\"><h2>Flop</h2></font><br/>pot(<b>"+spot+"</b>)";
	flo->setText( stex.c_str() );
}

/*
 * Lorsque que l'un des 2 joueurs n'a plus d'argent il perd la partie
 * Cette fonction met fin au timer, la seul utilisation possible de l'application reste les onglets
 */
void QtApp::endGame(Player &player1,Player &player2)
{

	if(player1.getBankrollInt() <= 0 || player2.getBankrollInt() <= 0)
	{
		if( Game::getGame()->gameinfo.getwinner() ==2 ) //player1.getBankrollInt() <= 0)
		{
			upadteInterfaceGraphicOnPlayer(player1);
			upadteInterfaceGraphicOnPlayer(player2);

			string libelle = "Le gagnant est : ";
			libelle.append( player2.getName().toStdString() );
			libelle.append( "-" );
			libelle.append( player2.getCombinationLabel().toStdString() );
			QMessageBox::information(this, "Partie fini", libelle.c_str() );
			timer->stop();
		}
		else if( Game::getGame()->gameinfo.getwinner()==1 )//player2.getBankrollInt() <= 0)
		{
			upadteInterfaceGraphicOnPlayer(player1);
			upadteInterfaceGraphicOnPlayer(player2);

			string libelle = "Le gagnant est : ";
			libelle.append( player1.getName().toStdString() );
			libelle.append( "-" );
			libelle.append( player1.getCombinationLabel().toStdString() );
			QMessageBox::information(this, "Partie fini", libelle.c_str() );
			timer->stop();
		}
	}
}

QtApp::QtApp(QWidget *parent)
{
	this->setParent(parent);

	//Gestion des onglets
	tab = new QTabWidget(this);
	QWidget *page = new QWidget;
	tab->addTab(page, "Partie 1");
	tab->setFixedSize(1200, 700);

	//Ajout du layout
	gridLayout = new QGridLayout();
	gridLayoutCardPlayer[0] = new QGridLayout();
	gridLayoutCardPlayer[1] = new QGridLayout();
	gridLayoutCardFlop = new QGridLayout();

	gridLayout->addLayout(gridLayoutCardPlayer[0],2,0);
	gridLayout->addLayout(gridLayoutCardFlop,2,1);
	gridLayout->addLayout(gridLayoutCardPlayer[1],2,2);
	page->setLayout(gridLayout);
}
// fonction appela toute les 1.5 secondes /
void QtApp::slotsConnexion()
{
	Server sr;
	sr.goPlayer(argvGolbal,this);
}
void QtApp::launch_in_main()
{
	this->setFixedSize(1200, 700);

	// Show windows
	this->show();
}

void QtApp::launch_in_new()
{
	//Game::getGame()->gameinfo.setCurrentPlayer(1);

 	//Create title
	titre = new QLabel("<font color=\"#FF0000\"><h2>Partie</h2></font>");
	gridLayout->addWidget(titre,0,0);

	// all 3 secondes call to slotsConnexion
	timer = new QTimer(this);

	// connexion slot
	QObject::connect(timer, SIGNAL(timeout()), this, SLOT(slotsConnexion()));
    timer->start(3000);
}
